local nfs   = require "nixio.fs"
local json = require "luci.jsonc"
require"luci.sys"
arg[1]=arg[1]or""
m=SimpleForm("nwt","设备".." - "..arg[1],"修改设备信息")
m.redirect=luci.dispatcher.build_url("admin/nwt/device")
m.reset=false
newname=m:field(Value,"_devicename","设备名称",
"15个字符以内，允许: <code>A-Z</code>, <code>a-z</code>, <code>0-9</code> 和 <code>_</code>"
)
newname.datatype="and(uciname,maxlength(15))"

newaddr=m:field(Value,"_deviceaddr","设备地址码",
"设备地址码不能修改")
newaddr.datatype="and(digit,rangelength(6,6))"
newaddr.readonly = true

local ctrl = require "luci.tools.nwt"
local devicelist = ctrl.get_devicelist()
if type(devicelist) == "table" then
	for _,device in pairs(devicelist) do
		if device.address == arg[1] then
			newname.value = device.name
			newaddr.value = device.address
		end
	end
end

function newname.validate(o,a,e)
	local addr=newaddr:formvalue(e)
	local exist = false
	if addr and#addr>0 then
		local nwtconf = json.parse(nfs.readfile("/etc/nwt.json") or "")
		if type(nwtconf) == "table" and nwtconf.devices then
			for _,value in pairs(nwtconf.devices) do
				if addr == value.address then
					exist = true
				end
			end
		end
	end
	if exist then
		return a
	else
		return nil,"设备不存在"
	end
end

function newname.write(e,a,n)
	local addr=newaddr:formvalue(a)
	if addr and#addr>0 then
		local devname=newname:formvalue(a)
		local nwtconf = json.parse(nfs.readfile("/etc/nwt.json") or "")
        if type(nwtconf) == "table" and nwtconf.devices then
			local deviceinfo = nwtconf.devices
        	for _,device in pairs(deviceinfo) do
				if addr == device.address then
					device.name = devname
				end
			end
        	local js = json.stringify(nwtconf)
			nfs.writefile("/etc/nwt.json",js)
        end
        luci.http.redirect(luci.dispatcher.build_url("admin/nwt/device"))
	end
end

return m

